/*
 * @Author: heinan
 * @Date: 2023-07-27 16:14:21
 * @Last Modified by: heinan
 * @Last Modified time: 2023-08-02 22:44:18
 */
const fs = require("fs/promises");
const path = require("path");
const { Controller } = require("egg");
const { nameCreator } = require("../utils");

/**
 *@Controller 公共服务
 */
class CommonController extends Controller {
  /**
   * @Summary 上传接口
   * @Router POST /upload
   * @Description 上传文件并返回存储服务器地址
   * @Request formData file *file
   */
  async upload() {
    const file = this.ctx.request.files[0];
    const filePath = path.normalize(file.filepath);
    const filename = nameCreator(file.filename);
    const error = await this.ctx.service.common.upload(filePath, filename);
    if (!error) {
      this.ctx.body = {
        code: 1,
        message: "上传成功！",
        url: `http://111.67.201.44:7001/upload/${filename}`,
      };
      await fs.unlink(filePath);
    } else {
      this.ctx.body = {
        code: 1,
        message: "上传成功！",
        error,
      };
    }
  }
}
module.exports = CommonController;
